package su.mvc.action.mail;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import su.mvc.action.ActionSupport;
import su.mvc.service.MailService;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

@Results(value = {
        @Result(name=ActionSupport.SUCCESS, location="mail.jsp"),
        @Result(name = ActionSupport.REDIRECT_OK, type = "redirect", location = "/mail/mail", params = {"messages", "mail.sent.successfully"}),
        @Result(name = ActionSupport.REDIRECT_CANCEL, type = "redirect", location = "/mail/mail")
})
public class MailAction extends ActionSupport{

    private static final Logger log = Logger.getLogger(MailAction.class.getName());


    MailService mailService;
    
    private String content;
    
    private String fromMail;
    
    private String fromName;
    
    private String subject;

    public MailService getMailService() {
        return mailService;
    }

    public void setMailService(MailService mailService) {
        this.mailService = mailService;
    }

    public String execute() throws Exception {
        return SUCCESS;
    }
    
    public String send() throws Exception {
        if (validateForm()) {
            Map<String, String> props = new HashMap<String, String>();
            props.put("text", content);
            mailService.sendMail(fromMail, fromName, subject, "feedback", props);
            return REDIRECT_OK;
        } else {
            return SUCCESS;
        }
    }
    
    public boolean validateForm() {
        if (StringUtils.isEmpty(fromMail)) addError("error.mail.from.email.empty");
        if (StringUtils.isEmpty(fromName)) addError("error.mail.from.name.empty");
        if (StringUtils.isEmpty(content)) addError("error.mail.content.empty");
        return getActionErrors().isEmpty();
    }
    
    public String cancel() throws Exception{
        return REDIRECT_CANCEL;
    }


    public void addMessage(String message) {
        addActionMessage(getText(message));
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getFromMail() {
        return fromMail;
    }

    public void setFromMail(String fromMail) {
        this.fromMail = fromMail;
    }

    public String getFromName() {
        return fromName;
    }

    public void setFromName(String fromName) {
        this.fromName = fromName;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }
}
